const express = require('express');
const router = express.Router();
const {
	skuProductListModel,
	categoryListModel,  
	cartListModel
} = require('../model/product') 

// 获取商品分类
router.get('/category', async (req, res) => {
	const data = await categoryListModel.find()
	const skuProductList = await skuProductListModel.find()

	res.send({
		code: 201,
		msg: '获取成功',
		data
	})
}); 

// 根据分类id获取商品
router.get('/product/:categoryId', async (req, res) => { 
	let categoryList = await categoryListModel.find()
	let { categoryId } = req.params
	let skuProductList = []
	if (categoryId != 0) {
		skuProductList = await skuProductListModel.find({categoryId})
	} else {
		skuProductList = await skuProductListModel.find({categoryId : categoryList[0].id})
	} 
	
	res.send({
		code: 201,
		data : skuProductList
	})
})

// 加入购物车
router.post('/addToCart', async (req, res) => {
	let {skuId,skuNum} = req.body
	let list = await cartListModel.find({ skuId }) 
	// 判断购物车中是否有当前商品
	if(list.length == 1){
		if (skuNum == 0) {
			await cartListModel.deleteOne({ skuId })
		} else {
			await cartListModel.updateOne({skuId }, {skuNum})
		}
	}else{
		await cartListModel.create(req.body)
	}

	res.send({
		code: 200,
		msg: '添加购物车成功'
	})
});

// 根据获取商品详情
router.get('/detail/:_id', async (req, res) => {
	console.log(req.params);
	let list = await skuProductListModel.find({ _id: req.params._id })
	let obj = list[0] 
	res.send({
		data: obj,
		code : 200
	})
})

module.exports = router;